import { system, world } from "@minecraft/server";
import { CubeRegion } from "@sapi-game/gameRegion/gameRegion";
import { Game, GameComponent } from "@sapi-game/main";
import { PillarOfFortuneMainState } from "../states/mainState";

export class PillarOfFortunePlayerLimiter extends GameComponent<PillarOfFortuneMainState> {
    private insetRegion?: CubeRegion;

    override onAttach(): void {
        this.insetRegion = this.context.map.region.inSet({ x: 1, y: 2, z: 1 });
        this.subscribe(Game.events.interval, () => {
            this.limitLocation();
            this.outBorderWarn();
        });
        //防止挖方块
        this.subscribe(world.beforeEvents.playerBreakBlock, (t) => {
            const gamePlayer = this.context.players.getById(t.player.id);
            if (!gamePlayer) return;
            if (!this.context.map.region.isInside(t.block.location)) {
                t.cancel = true;
                system.run(() => {
                    gamePlayer.actionbar("你不能破坏地图外的方块");
                });
            }
        });
        //防止放方块
        this.subscribe(world.beforeEvents.playerInteractWithBlock, (t) => {
            const gamePlayer = this.context.players.getById(t.player.id);
            if (!gamePlayer) return;
            if (!this.insetRegion!.isInside(t.block.location)) {
                t.cancel = true;
                system.run(() =>
                    gamePlayer.actionbar("你不能在地图外放置方块")
                );
            }
        });
    }

    /**限制活动区域 */
    limitLocation() {
        const region = this.context.outSetRegion;
        if (!region) return;
        this.context.players.forEach((p) => {
            if (!p.alive) return;
            if (!region.isInside(p.player.location)) {
                p.sendMessage("你超出了边境,寄了");
                p.alive = false;
                p.player.kill();
            }
        });
    }

    outBorderWarn() {
        this.context.players.forEach((p) => {
            if (!p.alive) return;
            if (!this.insetRegion!.isInside(p.player.location)) {
                system.run(() => {
                    p.actionbar("§c你即将到达地图边界，超过会死亡");
                });
            }
        });
    }
}
